import pinsInputLess from "./pinsInput.module.less";
import { useState, useEffect, useRef } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Input, Popover, Upload, Image, message } from "antd";
import Picker from "@emoji-mart/react";
const { TextArea } = Input;
import data from "@emoji-mart/data";
import { UploadApi } from "@/http/api/upload";
import PinUrl from "@/components/pinUrl/pinUrl";
import PinsLabel from "@/components/pinsLabel/pinsLabel";
import type { GetProp, UploadFile, UploadProps } from "antd";
import { GetActivityListApi } from "@/http/api/article";
import { AnalysisUrlApi } from "@/http/api/other";
import { CreatePinApi } from "@/http/api/pin";
import { GetCircleTypeListApi, GetCircleListApi } from "@/http/api/circle";

import VirtualList from "rc-virtual-list";
type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

interface ActivityType {
  ActivityId: number;
  ActivityTitle: string;
  // 其他属性...
}
function PinsInput({ reflash }: any) {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [Activity, setActivityList] = useState<ActivityType[]>([]);
  const [setTimeoutOpticeList, setSetTimeOutOpticeList] = useState(
    setTimeout(() => {})
  );
  const searchKey = useRef("");
  const [circleSearchKey, setCircleSearchKey] = useState("");
  const [urlValue, seturlValue] = useState("");
  const [urlTitle, setUrlTitle] = useState("");
  const [urlIoc, setUrlIoc] = useState("");
  const [open, setOpen] = useState(false);
  const [circleOpen, setOpenCircle] = useState(false);
  const [openTopice, setOpenTopice] = useState(false);
  const [realyUrl, setRealUrl] = useState("");
  const [analysisBtn, setAnalysisBtn] = useState(false);
  const [TotalCount, setTotalCount] = useState(0);
  const [PageSize, setPageSize] = useState(10);
  const [PageNum, setPageNum] = useState(1);
  const [value, setValue] = useState("");
  const [focus, setFocus] = useState(false);
  const [num, setNum] = useState(0);
  const [circleTypeList, setCircleTypeList] = useState([]);
  const [activeCircleType, setActiveCircleType] = useState(1);
  const [circleList, setCircleList] = useState([]);
  const [fileList, setFileList] = useState<any>([]);
  const [pinsCircle, setPinsCircle] = useState("请选择圈子");
  const [CircleTypeId, setCircleTypeId] = useState(1);
  const [pinsCircleId, setPinsCircleId] = useState(null);
  const [hashtag, setHashtag] = useState(""); // 话题内容
  const [ActivityId, setActivityId] = useState(null); //话题ID
  const [textIndent, setTextIndent] = useState("0px"); // 动态缩进
  const hashtagRef = useRef<any>(null);
  const inputRef = useRef<any>(null);
  const divRef = useRef<any>(null);
  const handlePreviewUpload = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleRemoveUpload = (file: UploadFile) => {
    console.log(3333, file);
    let NewFileList = fileList.filter((item: any) => item.uid !== file.uid);
    setFileList(NewFileList);
  };
  const uploadButton = (
    <button
      style={{
        border: 0,
        background: "none",
        fontSize: 20 + "px",
        color: "#d1d2d2",
      }}
      type="button"
    >
      <PlusOutlined />
    </button>
  );

  const TextAreaInput = (e: any) => {
    setNum(e.target.value.length);
  };
  const handleKeyDown = (e: any) => {
    // 检测按键是否是 Backspace 并文本为空
    const cursorPosition = e.target.selectionStart;
    if (
      (e.code === "Backspace" || e.code === "Delete") &&
      cursorPosition === 0
    ) {
      setHashtag(""); // 清空话题
      setActivityId(null);
    }
  };
  const selectEmoji = (e: any) => {
    console.log(3333, e, inputRef.current);
    const textArea = document.getElementById(
      "textArea"
    ) as HTMLTextAreaElement | null;
    const cursorPosition = textArea?.selectionStart; // 获取光标位置
    const newText =
      value.slice(0, cursorPosition) + e.native + value.slice(cursorPosition);
    setValue(newText);
    setNum(newText.length);
    let selectionStart = cursorPosition + e.native.length;
    console.log(999999, cursorPosition, selectionStart);
    inputRef.current!.focus({
      cursor: "start",
    });
    /*   inputRef.selectionStart = cursorPosition; */
  };
  // 处理点击事件，阻止失去焦点
  const handleClickInside = (e: any) => {
    console.log("点击", e);
    /* const textArea = document.getElementById(
      "textArea"
    ) as HTMLTextAreaElement | null;
    const cursorPosition = textArea?.selectionStart;
    console.log(47444, cursorPosition);
    inputRef.selectionStart = cursorPosition; */
    /*   */
  };

  const CreatePin = async () => {
    const params = {
      ArticleContent: value,
      Attachment: fileList,
      UrlTitle: urlTitle,
      RealyUrl: realyUrl,
      ActivityId: ActivityId,
      CircleId: pinsCircleId,
      CircleTypeId: CircleTypeId,
    };
    const res: any = await CreatePinApi(params);
    console.log("创建沸点", res);
    if (res.status === 0) {
      message.success("发布成功");
      clearAll();
      reflash();
    } else {
      message.error(res.msg);
    }
  };

  const clearAll = () => {
    setValue("");
    setFileList([]);
    setUrlTitle("");
    setRealUrl("");
    setActivityId(null);
    setPinsCircleId(null);
    setCircleTypeId(1);
  };

  const publishClick = () => {
    if (!value) {
      message.error("内容不能为空");
      return;
    }
    CreatePin();
  };

  // 处理点击输入框外部时失去焦点
  const handleOutsideClick = (e: any) => {
    if (divRef.current && !divRef.current.contains(e.target)) {
      inputRef.current!.blur();
      setFocus(false);
    }
  };
  // 监听点击事件，点击外部关闭时失去焦点
  useEffect(() => {
    document.addEventListener("mousedown", handleOutsideClick); // 监听全局点击
    return () => {
      document.removeEventListener("mousedown", handleOutsideClick); // 清理监听
    };
  }, []);
  const FuemojiClick = () => {};
  const content = (
    <Picker
      data={data}
      onEmojiSelect={selectEmoji}
      locale={"zh"}
      set={"native"}
      previewPosition={"none"}
      searchPosition={"none"}
    />
  );

  const checkUrl = async () => {
    const params = {
      url: urlValue,
    };
    const res: any = await AnalysisUrlApi(params);
    console.log("解析url地址结果", res);
    if (res.status === 0) {
      /* seturlValue(res.url); */
      setOpen(false);
      setUrlTitle(res.urlTitle);
      setUrlIoc(res.urlImage);
      setRealUrl(res.domain);
      seturlValue("");
    } else {
      message.error(res.msg);
      setUrlTitle(urlValue);
    }
    setAnalysisBtn(false);
  };

  const Analysisurl = () => {
    if (analysisBtn) return;
    setAnalysisBtn(true);
    checkUrl();
  };

  const urlInputOnChange = (e: any) => {
    console.log(333, e.target.value, urlValue);
    seturlValue(e.target.value);
  };
  const closeUrl = () => {
    seturlValue("");
    setUrlTitle("");
    setUrlIoc("");
    setRealUrl("");
  };
  const contentlink = (
    <div className={pinsInputLess.linkContent}>
      <div className="linkInput">
        <Input
          placeholder="添加网页链接,自动识别"
          onChange={urlInputOnChange}
          value={urlValue}
          allowClear
        />
      </div>
      <div
        className={[analysisBtn ? "btn_forbidden" : "", "btn"].join(" ")}
        onClick={Analysisurl}
      >
        {!analysisBtn && <div className="icon iconfont icon-tianjia"></div>}
        <div className="tips">{analysisBtn ? "解析中..." : "解析"}</div>
      </div>
    </div>
  );
  const GetActivityList = async (type: String) => {
    console.log("获取列表", searchKey.current);
    const params = {
      PageSize: PageSize,
      PageNum: PageNum,
      Type: 2,
      Filter: searchKey.current,
    };
    const res: any = await GetActivityListApi(params);
    console.log("获取话题列表", res);
    if (res.status === 0) {
      if (type === "bottom") {
        setActivityList([...Activity, ...res.ActivityList]);
      } else {
        setActivityList(res.ActivityList);
      }
      setTotalCount(res.TotalCount);
    }
  };
  const appendData = () => {
    if (Activity.length < TotalCount) {
      console.log("bottombottombottom", Activity.length, TotalCount);
      setPageNum(PageNum + 1);
      GetActivityList("bottom");
    } else {
    }
  };
  const ContainerHeight = 300;
  const onScroll = (e: React.UIEvent<HTMLElement, UIEvent>) => {
    console.log("滚动触发");
    if (
      Math.abs(
        e.currentTarget.scrollHeight -
          e.currentTarget.scrollTop -
          ContainerHeight
      ) <= 1
    ) {
      appendData();
    }
  };
  const inputOnChange = (e: any) => {
    console.log("inputOnChange", e.target.value);
    searchKey.current = e.target.value;
    clearTimeout(setTimeoutOpticeList);
    setSetTimeOutOpticeList(
      setTimeout(() => {
        setPageNum(1);
        GetActivityList("");
      }, 500)
    );
  };
  const circleInputOnChange = (e: any) => {
    console.log("circleInputOnChange", e.target.value);
    setCircleSearchKey(e.target.value);
  };
  const selectTopice = (item: any) => {
    setHashtag(`#${item.ActivityTitle}#`);
    setActivityId(item.ActivityId);
    setOpenTopice(false);
    setValue(` ${value}`);
    inputRef.current!.focus({
      cursor: "end",
    });
  };
  const contentopic = (
    <div className={pinsInputLess.opicContent}>
      <div className="opicInput">
        <Input
          placeholder="搜索话题名称"
          onChange={inputOnChange}
          value={searchKey.current}
        />
        <div className="icon iconfont icon-sousuo"></div>
      </div>
      <div className="recommTopic">
        {Activity.length > 0 ? (
          <VirtualList
            data={Activity}
            height={ContainerHeight}
            itemHeight={47}
            itemKey="ActivityId"
            onScroll={onScroll}
          >
            {(item: any) => (
              <div
                className="itemsTop"
                key={item.ActivityId}
                onClick={() => selectTopice(item)}
              >
                <div className="leftIcon iconfont icon-rementuijian"></div>
                <div className="topice">#{item.ActivityTitle}#</div>
              </div>
            )}
          </VirtualList>
        ) : (
          <div className="nodata">
            <img src="/public/img/noOtherRes.avis" alt="" />
            <div className="tips">暂无相关结果</div>
          </div>
        )}
      </div>
    </div>
  );

  const GetCircleTypeListMethods = async () => {
    const res: any = await GetCircleTypeListApi();
    console.log("获取圈子类型列表", res);
    if (res.status === 0) {
      setCircleTypeList(res.CircleTypeList);
    }
  };

  const GetCircleListMethods = async () => {
    const params = {
      CircleTypeId: activeCircleType,
    };
    const res: any = await GetCircleListApi(params);
    console.log("获取圈子列表", res);
    if (res.status === 0) {
      setCircleList(res.CircleList);
    }
  };

  const selectType = (CircleTypeId: number) => {
    setActiveCircleType(CircleTypeId);
  };

  const selectCircle = (item: any) => {
    setPinsCircle(item.CircleTitle);
    setPinsCircleId(item.CircleId);
    setCircleTypeId(item.CircleTypeId);
    setOpenCircle(false);
  };

  const circle = (
    <div className={pinsInputLess.circleContent}>
      <div className="opicInput">
        <Input
          placeholder="搜索圈子名称"
          onChange={circleInputOnChange}
          value={circleSearchKey}
        />
        <div className="icon iconfont icon-sousuo"></div>
      </div>
      <div className="bottomList">
        <div className="leftList">
          <VirtualList
            data={circleTypeList}
            height={400}
            itemHeight={47}
            itemKey="CircleTypeId"
            onScroll={onScroll}
          >
            {(item: any) => (
              <div
                className={[
                  "leftItems",
                  activeCircleType === item.CircleTypeId
                    ? "leftItems_active"
                    : "",
                ].join(" ")}
                onClick={() => selectType(item.CircleTypeId)}
              >
                <div
                  className={[
                    "text",
                    activeCircleType === item.CircleTypeId ? "text_active" : "",
                  ].join(" ")}
                >
                  {item.CircleTypeName}
                </div>
              </div>
            )}
          </VirtualList>
        </div>
        <div className="rightList">
          {circleList.length > 0 ? (
            <VirtualList
              data={circleList}
              height={400}
              itemHeight={47}
              itemKey="CircleId"
            >
              {(item: any) => (
                <div className="rightItems" onClick={() => selectCircle(item)}>
                  <div className="rightCircleLeftimg">
                    <img
                      src={
                        item.CircleUrl ||
                        "https://img2.baidu.com/it/u=4116026810,839341703&fm=253&fmt=auto&app=138&f=JPEG?w=320&h=512"
                      }
                      alt=""
                    />
                  </div>
                  <div className="right_right_info">
                    <div className="topTitle">{item.CircleTitle}</div>
                    <div className="bottomTips">
                      {item.CirclePeople}掘友·{item.PinsNum}沸点
                    </div>
                  </div>
                </div>
              )}
            </VirtualList>
          ) : (
            <div className="nodata">
              <img src="/public/img/noOtherRes.avis" alt="" />
              <div className="tips">暂无相关结果</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
  const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    console.log(666666666, newFileList);
    /* setFileList(newFileList); */
  };

  const customRequest = async (file: any) => {
    console.log("customRequest", file);
    const form = new FormData();
    form.append("file", file.file);
    const res: any = await UploadApi(form);
    console.log("上传结果", res);
    if (res.status === 0) {
      console.log(3333, fileList);
      const NewFile = [
        {
          uid: String(fileList.length + 1),
          name: res.name,
          status: "done",
          url: res.url,
        },
      ];
      setFileList([...fileList, ...NewFile]);
      console.log("设置数组结果", fileList, [...fileList, ...NewFile]);
    }
    return false;
  };
  const handleOpenChange = (newOpen: boolean) => {
    setOpen(newOpen);
    if (!newOpen) seturlValue("");
  };
  const handleCircleOpenChange = (newOpen: boolean) => {
    setOpenCircle(newOpen);
    if (!newOpen) seturlValue("");
  };
  const selectEmojiClick = () => {
    /*  const textArea = document.getElementById("textArea");
    inputRef.current!.focus({
      selectionStart: textArea.selectionStart,
    }); */
  };
  const handleOpenTopiceChange = (newOpen: boolean) => {
    setOpenTopice(newOpen);
    if (!newOpen) seturlValue("");
  };
  // 动态计算话题宽度
  useEffect(() => {
    if (hashtagRef.current) {
      const hashtagWidth = hashtagRef.current.offsetWidth;
      const extraPadding = 5; // 话题后的额外空隙
      setTextIndent(`${hashtagWidth + extraPadding}px`);
    }
  }, [hashtag]);
  useEffect(() => {
    GetCircleListMethods();
  }, [activeCircleType]);
  useEffect(() => {
    GetActivityList("");
    GetCircleTypeListMethods();
    GetCircleListMethods();
  }, []);
  return (
    <>
      <div className={pinsInputLess.pinsInputContent}>
        <div
          className="inputContent"
          style={{
            borderColor: focus ? "#1e80ff" : "transparent",
          }}
        >
          <div className="topInput">
            <div className="topiceShow" ref={hashtagRef}>
              {hashtag}
            </div>
            <TextArea
              value={value}
              id="textArea"
              ref={inputRef}
              onChange={(e) => setValue(e.target.value)}
              onInput={TextAreaInput}
              onFocus={() => setFocus(true)}
              /*  onBlur={() => setFocus(false)} */
              onKeyDown={handleKeyDown}
              placeholder="快和掘友一起分享新鲜事!告诉你个小秘密，发布沸点时添加圈子和话题会被更多掘友看到哦~"
              autoSize={{ minRows: 3, maxRows: 5 }}
              maxLength={1000}
              style={{
                flex: 1,
                border: "none",
                textIndent,
                backgroundColor: focus ? "#ffffff" : "#f2f3f5",
                transition: "none",
              }}
            />
          </div>
          <div
            className="botttom_info"
            style={{
              backgroundColor: focus ? "#ffffff" : "#f2f3f5",
            }}
          >
            <Popover
              placement="bottom"
              content={circle}
              open={circleOpen}
              onOpenChange={handleCircleOpenChange}
              overlayClassName={pinsInputLess.nopadding}
              trigger="click"
            >
              <div className="infoSelect" onClick={() => setOpenCircle(true)}>
                <PinsLabel focus={focus} LabelName={pinsCircle} />
              </div>
            </Popover>

            {/* img */}
            {fileList.length > 0 && (
              <div className="AttchmentComponents">
                <Upload
                  customRequest={customRequest}
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={handlePreviewUpload}
                  onRemove={handleRemoveUpload}
                  onChange={handleChange}
                  multiple
                  maxCount={9}
                >
                  {fileList.length >= 8 ? null : uploadButton}
                </Upload>
                {previewImage && (
                  <Image
                    wrapperStyle={{ display: "none" }}
                    preview={{
                      visible: previewOpen,
                      onVisibleChange: (visible) => setPreviewOpen(visible),
                      afterOpenChange: (visible) =>
                        !visible && setPreviewImage(""),
                    }}
                    src={previewImage}
                  />
                )}
              </div>
            )}
            {/* url */}
            {urlTitle && (
              <PinUrl
                urlTitle={urlTitle}
                realyUrl={realyUrl}
                closeUrl={closeUrl}
              />
            )}
          </div>
          <div className="right_input_num">
            <span>{num}</span>/1000
          </div>
        </div>
        <div
          className="bottom_control"
          ref={divRef}
          onMouseDown={handleClickInside}
        >
          <div className="left_input_type">
            <Popover
              placement="bottom"
              content={content}
              trigger="click"
              onOpenChange={selectEmojiClick}
            >
              <div className="type_items" onClick={FuemojiClick}>
                <div className="icon iconfont icon-biaoqing"></div>
                <div className="name">表情</div>
              </div>
            </Popover>
            <Upload
              customRequest={customRequest}
              multiple
              showUploadList={false}
            >
              <div className="type_items">
                <div className="icon iconfont icon-tupian"></div>
                <div className="name">图片</div>
              </div>
            </Upload>
            <Popover
              placement="bottomLeft"
              title={null}
              open={open}
              onOpenChange={handleOpenChange}
              trigger="click"
              content={fileList.length > 0 ? null : contentlink}
            >
              <div
                className="type_items"
                style={{
                  cursor: fileList.length > 0 ? "not-allowed" : "pointer",
                  color: fileList.length > 0 ? "#c5c8cf" : "",
                }}
              >
                <div className="icon iconfont icon-lianjie"></div>
                <div className="name">链接</div>
              </div>
            </Popover>
            <Popover
              placement="bottomLeft"
              title={null}
              trigger="click"
              open={openTopice}
              onOpenChange={handleOpenTopiceChange}
              content={contentopic}
              overlayClassName={pinsInputLess.nopadding}
            >
              <div className="type_items">
                <div className="icon iconfont icon-huati"></div>
                <div className="name">话题</div>
              </div>
            </Popover>
          </div>
          <div className="right_btn">
            <div
              className="btn"
              onClick={publishClick}
              style={{
                backgroundColor: num ? "#1e80ff" : "#abcdff",
                cursor: num ? "pointer" : "not-allowed",
              }}
            >
              发布
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
export default PinsInput;
